<template>
  <div class="container">
    <h1 style="text-align: center;margin-bottom: 0;margin-top: 50px;color: #ff4800;margin-left: 50px">添加秒杀商品</h1>
    <div style="display: flex;justify-content: center">
      <el-form :rules="rules" ref="formData" :model="formData" label-width="100px" label-position="right" status-icon>

        <el-form-item label="商品标题：" prop="goodsTitle" style="margin-top: 40px">
          <el-input v-model.trim="formData.goodsTitle" placeholder="请输入商品标题" maxlength="150"></el-input>
        </el-form-item>
        <el-form-item label="商品简介：" prop="goodsContent" style="margin-top: 40px">
          <el-input v-model.trim="formData.goodsContent" placeholder="请输入商品简介" maxlength="150"></el-input>
        </el-form-item>
        <el-form-item label="商品单价：" prop="goodsPrice">
          <el-input v-model.trim="formData.goodsPrice" placeholder="请输入商品单价"
                    oninput="value=value.replace(/[^\d.]/g,'')"
          ></el-input>
        </el-form-item>
        <el-form-item label="秒杀价格：" prop="seckillPrice">
          <el-input v-model.trim="formData.seckillPrice" oninput="value=value.replace(/[^\d.]/g,'')"
                    placeholder="请输入商品秒杀价"
          ></el-input>
        </el-form-item>
        <el-form-item label="库存：" prop="goodsStock">
          <el-input type="number" v-model.trim="formData.goodsStock"
                    onkeypress="return( /[\d]/.test(String.fromCharCode(event.keyCode) ) )"
                    autocomplete="off" placeholder="请输入商品库存"
          ></el-input>
        </el-form-item>
        <el-form-item label="开始时间：" prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            type="datetime"
            style="width: 100%"
            placeholder="选择秒杀开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间：" prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            type="datetime"
            style="width: 100%"
            placeholder="选择秒杀结束时间"
          >
          </el-date-picker>
        </el-form-item>


        <el-form-item label="商品图片：" prop="imageUrl">
          <img :src="formData.goodsImg" v-if="formData.goodsImg!=null" title="点击上传商品图片" class="avatar"
               @click="toggleShow" style="width: 450px;height: 450px"
          >
          <span v-if="formData.goodsImg==null" @click="toggleShow">点击上传商品图片</span>
          <my-upload
            @crop-success="cropSuccess"
            @crop-upload-success="cropUploadSuccess"
            @crop-upload-fail="cropUploadFail"
            field="file"
            v-model="show"
            :headers="{'satoken': this.$store.getters.token}"
            :url="url"
            method="post"
          />
        </el-form-item>
        <h3 style="text-align: center;margin-left: 10px;margin-top: 0px">商品详情</h3>
        <el-form-item prop="goodsDetailMd" label-width="20px">
          <mavon-editor :autofocus="false"
                        ref="md"
                        v-model="formData.goodsDetailMd"
                        codeStyle="tomorrow-night"
                        @change="getMdHtml"
                        @imgAdd="uploadContentImg"
                        @imgDel="delContentImg"
                        class="my_markdown"
                        style="max-width: 1200px"
          />
        </el-form-item>
        <el-form-item style="width: 100%;text-align: center" label-width="10px">
          <el-button type="primary" @click="submitForm('formData')" size="mini">发布</el-button>
          <el-button size="mini" @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
import 'babel-polyfill' // es6 shim
import myUpload from 'vue-image-crop-upload/upload-2.vue'
import commonApi from '@/api/common'
import api from '@/api/goods'

// 引入 mavonEditor 组件和样式, 一定不要少了大括号
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

export default {

  name: 'edit',
  components: {
    'my-upload': myUpload,
    mavonEditor
  },

  props: {
    formData: { // 提交表单数据
      type: Object,
      default: {}
    },
    remoteClose: Function // 用于关闭窗口
  },
  data() {
    const validateStartTime = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入开始时间'))
      } else {
        if (new Date(this.formData.startDate).getTime() <= new Date().getTime()) {
          callback(new Error('开始时间必须大于当前时间！'))
        } else {
          callback()
        }
      }
    }
    const validateEndTime = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入截止时间'))
      } else {
        if (
          new Date(this.formData.startDate).getTime() >=
          new Date(this.formData.endDate).getTime()
        ) {
          callback(new Error('截止时间必须大于开始时间！'))
        } else {
          callback()
        }
      }
    }
    return {
      url: 'http://localhost:8082/pri/file/upload/user',
      // 校验表单
      rules: {
        goodsTitle: [
          { required: true, message: '请输入商品标题', trigger: 'blur' },
          { min: 6, max: 150, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ],
        goodsPrice: [
          { required: true, message: '请输入商品单价', trigger: 'blur' }
        ],
        seckillPrice: [
          { required: true, message: '请输入商品秒杀价', trigger: 'blur' }
        ],
        goodsStock: [
          { required: true, message: '请输入商品库存', trigger: 'blur' }
        ],
        isAccountNonExpired: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        startDate: [
          { required: true, message: '请输入秒杀开始时间', trigger: 'blur' },
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            validator: validateStartTime
          }
        ],
        endDate: [
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            validator: validateEndTime
          }
        ],
        isCredentialsNonExpired: [
          { required: true, message: '请选择', trigger: 'change' }
        ],

        isAccountNonLocked: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      show: false
    }
  },
  created() {
    this.getData(this.$route.query.id)
  },
  methods: {
    // 编辑-获取数据
    getData(id){
      if (id!=null) {
        api.getById(id).then(response => {
          if (response.code === 20000) {
            this.formData = response.data
          }
        })
      }
    },
    getMdHtml(mdContent, htmlContent) {
      this.formData.goodsDetailMd = mdContent
      this.formData.goodsDetail = htmlContent
    },
    uploadContentImg(pos, file) {
      // 第一步，将图片上传到服务器
      let fd = new FormData()
      fd.append('file', file)
      commonApi.uploadImg(fd).then(response => {
        console.log(response)
        // 第二步，将返回的url替换到文件位置
        this.$refs.md.$img2Url(pos, response.data)
      })
    },
    // 删除内容图片
    delContentImg(urlAndFileArr) {
      const fileUrl = urlAndFileArr[0]
      const file = urlAndFileArr[1]
      commonApi.delContentImg(fileUrl)
    },
    cropSuccess(imgDataUrl, field) {
      this.formData.goodsImg = imgDataUrl
    },
    cropUploadSuccess(jsonData, field) {
      console.log(jsonData)
      this.formData.goodsImg = jsonData.data
    },
    cropUploadFail(status, field) {
      this.$message.error('图像上传失败')
    },
    toggleShow() {
      this.show = !this.show
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 校验通过，提交表单数据
          this.submitData()
        } else {
          return false
        }
      })
    },

    async submitData() {
      let response = null
      if (this.formData.id) {
        // 编辑
        response = await api.update(this.formData)
      } else {
        // 新增
        // 初始密码与用户名一致
        this.formData.password = this.formData.username
        response = await api.add(this.formData)
      }

      if (response.code = 20000) {
        this.$message({ message: '保存成功', type: 'success' })
        this.$router.push({ name: 'goods' })
        this.handleClose()
      } else {
        this.$message({ message: '保存失败', type: 'error' })
      }
    },

    // 关闭窗口
    handleClose() {
      this.$router.push({ name: 'goods' })
      this.show = false
      this.$refs['formData'].resetFields()
      this.remoteClose()
    }
  }
}
</script>

<style scoped>
.my_markdown {
  height: 60vh;
}
</style>
